<template>
  <div class="combox">
    <!-- <div class="titlebox">评论区</div> -->
    <div class="inputbox">
      <div class="area">
        <el-input
          :placeholder="placeholder"
          minlength="2"
          maxlength="7"
          v-model="userName"
          :disabled="disabled"
          v-if="!disabled"
        ></el-input>
        <el-input
          type="textarea"
          placeholder="撰写评论"
          minlength="2"
          maxlength="150"
          show-word-limit
          resize="none"
          rows="4"
          v-model="content"
          id="textpanel"
        ></el-input>
      </div>
      <div class="e_center">
        <div class="e_left">
          <div class="emoji_box">
            <img
              class="emoji-panel-btn"
              src="/images/face.png"
              @click="changeShow"
            />
            <chat-emoji
              class="emoji"
              :page="type"
              @addEmoji="appendEmoji"
              v-show="showEmoji"
            ></chat-emoji>
          </div>
          <div class="imgbox">
            <img
              v-if="!getToken"
              class="emoji-panel-btn select-img"
              src="/images/avatars.png"
              @click="changeAvatars"
            />
            <span
              v-if="!getToken"
              v-html="imgSrc ? '用户头像:' : '未选择用户头像'"
            ></span>
            <img class="emoji-panel-btn" :src="imgSrc" alt="" />

            <div class="avatars_box" v-show="showAvatars">
              <div v-for="(item, index) in 8" :key="index">
                <img
                  :src="'/images/' + item + '.png'"
                  alt=""
                  :class="index == currentIndex ? 'active' : ''"
                  @click="changeIndex(index)"
                />
              </div>
            </div>
          </div>
        </div>
        <div class="user">
          <el-button
            type="primary"
            style="height:40px;margin-left:30px;verticalAlign: bottom;"
            @click="postCom"
            >发表评论</el-button
          >
        </div>
      </div>
    </div>
    <div tag="div" name="list" class="comment">
      <div class="com_title">
        <span class="t_text">评论</span
        ><span class="t_border">{{ count }}条评论</span>
      </div>
      <div v-for="(item, index) in articleCom" class="item" :key="index">
        <div class="com_user">
          <div class="user_img">
            <img v-if="item.user.isAdmin" :src="getAdmin.photo" alt="" />
            <img
              v-else-if="!item.user.isAdmin && item.user.photo"
              :src="item.user.photo"
              alt=""
            />
            <img v-else :src="'/images/' + ((index % 7) + 1) + '.png'" alt="" />
          </div>
          <div class="user_name">
            <div class="from">
              {{ item.user.isAdmin ? getAdmin.userName : item.user.name }}
              <i class="isAdmin" v-if="item.user.isAdmin">博主</i>
              <!-- <i class="isAdmin">博主</i> -->
            </div>
            <div class="time">{{ item.date | chatDateFormate }}</div>
          </div>
        </div>
        <div class="info">
          <div class="htmlcom" v-html="item.content"></div>
          <div class="operation">
            <i
              class="el-icon-delete delete"
              @click="deleteCom(item._id)"
              v-if="$store.state.isLogin"
            ></i>
            <i
              class="iconfont icon-message"
              @click="changeParentIndex(index)"
              style="fontSize:15px"
              >({{ item.children.length }})</i
            >
          </div>
          <div v-if="index == parentIndex">
            <com-item
              top="-80px"
              left="0px"
              width="400px"
              :inputID="'text' + index"
              @handleCom="
                handleCom($event, {
                  toUser: item.user,
                  id: item._id,
                  comment: item.content,
                })
              "
            ></com-item>
            <div class="childcomt" v-if="item.children.length">
              <div
                class="child_item"
                v-for="(item2, index2) in item.children"
                :key="index2"
              >
                <div class="namebox">
                  <div class="child_avatars">
                    <img
                      :src="
                        item2.fromUser.isAdmin
                          ? getAdmin.photo
                          : item2.fromUser.photo
                      "
                      alt=""
                    />
                  </div>
                  <div class="child_info">
                    <div class="from">
                      {{
                        item2.fromUser.isAdmin
                          ? getAdmin.userName
                          : item2.fromUser.name
                      }}
                      <i class="isAdmin" v-if="item2.fromUser.isAdmin">博主</i>
                      <!-- <i class="isAdmin">博主</i> -->
                    </div>
                    <div class="c_time">
                      {{ item2.c_date | chatDateFormate }}
                    </div>
                  </div>
                </div>
                <div class="c_content">
                  <span class="to"
                    >@{{
                      item2.toUser.isAdmin
                        ? getAdmin.userName
                        : item2.toUser.name
                    }}
                    <i class="isAdmin" v-if="item2.toUser.isAdmin">博主</i>
                    <!-- <i class="isAdmin">博主</i> -->
                  </span>
                  <span>{{ item2.c_content }}</span>
                </div>
                <div class="c_other">
                  <i
                    class="el-icon-delete delete"
                    @click="deleteCom(item._id, item2.c_date)"
                    v-if="$store.state.isLogin"
                  ></i>
                  <i
                    class="iconfont icon-message"
                    @click="chageComIndex(index, index2)"
                    style="fontSize:15px"
                  ></i>
                </div>
                <div v-if="-Math.ceil(index + 1) + '' + index2 == comIndex">
                  <com-item
                    top="-80px"
                    left="0px"
                    width="400px"
                    :inputID="'child' + index2"
                    @handleCom="
                      handleCom($event, {
                        toUser: item2.fromUser,
                        id: item._id,
                        comment: item2.c_content,
                      })
                    "
                  ></com-item>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="pagebox">
      <el-pagination
        :page-size="limit"
        layout="prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
        :hide-on-single-page="true"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import comItem from "./comitem"
import ChatEmoji from "../chatEmoji/emoji"

import request from "../../api/request"

import { mapGetters } from "vuex"

export default {
  data() {
    return {
      placeholder: "",
      admin: "",
      disabled: false,
      articleCom: [],
      content: "",
      userName: "",
      showEmoji: false,
      total: 0,
      count: 0,
      page: 1,
      limit: 5,
      parentIndex: -1,
      comIndex: 0,
      currentIndex: -1,
      type: "other",
      imgSrc: "",
      showAvatars: false,
      commentType: "", //评论类型：评论（comment），回复(reply)
      user: null,
      childData: {},
    }
  },
  props: ["id", "title"],
  created() {
    this.getCom()
  },
  computed: {
    ...mapGetters(["getAdmin", "getToken", "getUser", "getIsLogin"]),
  },
  watch: {
    id: function(newVal, oldVal) {
      this.getCom()
    },
    getToken: function() {
      this.disabled = Boolean(this.getToken)
      if (this.commentType == "comment") {
        this.user.account = this.getUser.account
        this.comment()
      } else if (this.commentType == "reply") {
        if (this.childData && this.childData.fromUser) {
          this.childData.fromUser.account = this.getUser.account
        }
        this.childComment()
      }
    },
  },
  mounted() {
    this.disabled = Boolean(this.getToken)
    this.placeholder = this.getToken
      ? "已经登录，不需要输入用户名"
      : "请输入用户名"
  },
  components: {
    comItem,
    ChatEmoji,
  },
  methods: {
    changeShow() {
      this.showEmoji = !this.showEmoji
      this.showAvatars = false
    },
    changeAvatars() {
      this.showAvatars = !this.showAvatars
      this.showEmoji = false
    },
    handleCurrentChange(val) {
      this.page = val
      this.getCom()
      this.parentIndex = -1
      this.comIndex = 0
    },

    postCom() {
      this.commentType = "comment"
      if (this.getToken) {
        this.user = {
          account: this.getUser.account,
          name: this.getUser.userName,
          isAdmin: this.getUser.isAdmin,
          photo: this.getUser.photo,
        }
        this.comment()
      } else {
        if (this.userName == "" || this.comment == "") {
          this.$notify.error({
            title: "错误",
            message: "用户名或者评论不能为空",
          })
          return
        } else if (this.imgSrc == "") {
          this.$notify.error({
            title: "错误",
            message: "未选择用户头像",
          })
          return
        } else {
          this.user = {
            name: this.userName,
            isAdmin: false,
            photo: this.imgSrc,
          }
          // 进行静默注册
          this.$store.dispatch("silentRegistered", {
            userName: this.userName,
            photo: this.imgSrc,
          })
        }
      }
    },
    // 发表评论
    async comment() {
      let result = await request({
        url: "/comment/release",
        data: {
          article: this.id,
          arName: this.title,
          user: this.user,
          content: this.content,
          date: new Date(),
        },
        method: "post",
      })
      if (result.status) {
        this.$notify({
          title: "成功",
          message: result.msg,
          type: "success",
        })
        // if (!this.) {
        // }
        this.getCom()
        this.content = ""
        this.userName = ""
        this.showAvatars = false
        this.showEmoji = false
      } else {
        this.$notify.error({
          title: "错误",
          message: result.msg,
        })
      }
    },
    handleCom(child, obj) {
      this.commentType = "reply"
      this.childData = {
        article: this.id,
        arName: this.title,
        fromUser: child.fromUser,
        c_content: child.c_content,
        c_date: child.c_date,
        toUser: obj.toUser,
        parentId: obj.id,
        comment: obj.comment,
      }
      if (this.getToken) {
        this.childComment()
      } else {
        this.$store.dispatch("silentRegistered", {
          userName: child.fromUser.name,
          photo: child.fromUser.photo,
        })
      }
    },
    // 回复
    async childComment() {
      let result = await request({
        url: "/comment/obtain/child",
        data: this.childData,
        method: "post",
      })

      if (result.status) {
        this.$notify({
          title: "成功",
          message: result.msg,
          type: "success",
        })

        this.getCom()
        this.comIndex = 0
      } else {
        this.$notify.error({
          title: "错误",
          message: result.msg,
        })
      }
    },

    async getCom() {
      let result = await request({
        url: "/comment/obtain",
        data: {
          article: this.id,
          limit: this.limit,
          page: this.page,
        },
        method: "get",
      })
      this.articleCom = result.data.map((item) => {
        if (item.children) {
          item.children = item.children.reverse()
        }
        return item
      })
      this.total = result.total
      this.count = result.count
    },
    changeIndex(index) {
      this.imgSrc = "/images/" + (index + 1) + ".png"
      this.showAvatars = false
    },
    changeParentIndex(index) {
      if (this.parentIndex == index) {
        this.parentIndex = -1
      } else {
        this.parentIndex = index
      }
    },
    chageComIndex() {
      let index = -[Math.ceil(arguments[0] + 1) + "" + arguments[1]]
      if (this.comIndex == index) {
        this.comIndex = 0
      } else {
        this.comIndex = index
      }
    },
    // 删除评论
    async deleteCom() {
      var _id = arguments[0]
      var c_date = -1
      if (arguments.length == 2) {
        c_date = arguments[1]
      }
      let result = await request({
        url: "/comment/remove",
        data: {
          _id,
          c_date,
        },
        method: "post",
      })
      if (result.status) {
        this.$notify({
          title: "成功",
          message: result.msg,
          type: "success",
        })
        this.getCom()
      } else {
        this.$notify.error({
          title: "错误",
          message: result.msg,
        })
      }
    },
    // 添加表情
    appendEmoji(emoji) {
      this.content = this.content + emoji
      this.showEmoji = false
      let input_dom = document.getElementById("textpanel")
      input_dom.focus()
    },
  },
}
</script>
<style lang="scss" scoped>
@import "../../scss/common.scss";
@import "./comment.scss";
</style>
<style lang="scss">
.emoji-item-common {
  background: url("/images/emoji_sprite.png");
  display: inline-block;
  margin-top: 2px;
  &:hover {
    cursor: pointer;
  }
}
.emoji-size-small {
  // 表情大小
  zoom: 0.4;
  vertical-align: top;
}
.emoji-size-large {
  zoom: 0.5; // emojipanel表情大小
  margin: 4px;
}
.comments-list {
  margin-top: 20px;
  .comments-list-item {
    margin-bottom: 20px;
    .comments-list-item-heading {
      display: inline-block;
      img {
        height: 32px;
        width: 32px;
        border-radius: 50%;
        vertical-align: middle;
      }
      .comments-list-item-username {
        margin-left: 5px;
        font-weight: bold;
      }
    }
    .comments-list-item-content {
      margin: 10px 0px;
      border-bottom: 1px solid #cccccc;
      &:last-child {
        border-bottom: 0;
      }
      span {
        vertical-align: top;
      }
    }
  }
}
</style>
